package com.motherchild.admin.controller;

import com.motherchild.admin.dto.CartDTO;
import com.motherchild.admin.dto.OrderDTO;
import com.motherchild.admin.dto.OrderResponse;
import com.motherchild.admin.service.OrderService;
import com.motherchild.common.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/admin")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @GetMapping("/orders")
    public ApiResponse<OrderResponse> getOrders(
            @RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        List<OrderDTO> orders = orderService.getOrders(pageNo, pageSize);
        int total = orderService.getTotalOrders();
        // 创建 OrderResponse 对象
        OrderResponse orderResponse = new OrderResponse(orders, total);
        return ApiResponse.success(orderResponse); // 返回订单列表和总数
    }

    @GetMapping("/orders1/{userId}")
    public ApiResponse<OrderResponse> getUserOrders(
            @RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            @PathVariable Integer userId) {
        List<OrderDTO> orders = orderService.getUserOrders(pageNo, pageSize,userId);
        int total = orderService.getTotalOrders();
        // 创建 OrderResponse 对象
        OrderResponse orderResponse = new OrderResponse(orders, total);
        return ApiResponse.success(orderResponse); // 返回订单列表和总数
    }
    @PostMapping("/orders")
    public ApiResponse<OrderDTO> addOrder(@RequestBody OrderDTO orderDTO) {
        orderService.saveOrder(orderDTO); // 添加订单
        return ApiResponse.success(orderDTO); // 返回添加的订单
    }

    @PutMapping("/orders/{id}")
    public ApiResponse<OrderDTO> updateOrder(@PathVariable Long id, @RequestBody OrderDTO orderDTO) {
        orderDTO.setId(id); // 设置订单ID
        orderService.updateOrder(orderDTO); // 更新订单
        return ApiResponse.success(orderDTO); // 返回更新后的订单
    }

    @GetMapping("/deleteOrder/{id}")
    public ApiResponse<Void> deleteOrder(@PathVariable Integer id) {
        orderService.deleteOrder(id); // 删除订单
        return ApiResponse.success(); // 返回成功响应
    }

    @GetMapping("/orders/{id}")
    public ApiResponse<CartDTO> getOrderById(@PathVariable Integer id) {
        CartDTO order = null; // 获取单个订单
        try {
            order = orderService.getOrderById(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ApiResponse.success(order); // 返回订单
    }
}